<?php

namespace App\Imports;

use App\Models\Administrator;
use App\Models\Clue;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use PhpOffice\PhpSpreadsheet\Shared\Date;

class ClueImport implements ToCollection
{
    public $count = 0;
    public $errorMessage = null;
    public $source;

    /**
     * @param $source
     */
    public function __construct($source)
    {
        $this->source = $source;
    }


    /**
     * @param Collection $collection
     */
    public function collection(Collection $collection)
    {
        $headerRow = $collection->shift();
        $headers = collect([
            "日期",
            "客户昵称",
            "手机号",
            "微信号",
            "现居地",
            "备注"
        ]);

        if ($headers->diff($headerRow)->count()) {
            $this->errorMessage = '错误的表头,无法识别文件,请使用模板';
            return;
        }

        $data = [];
        foreach ($collection as $item) {
            $row = [];
            foreach ($headerRow as $index => $value) {
                $row[$value] = $item->get($index);
            }
            $data[] = $row;
        }


        foreach ($data as $row) {
            $phone = $row['手机号'];
            if (!$phone || !preg_match("/^1[3-9]\d{9}$/", $phone))
                continue;

            $postDate = $row['日期'];
            if (!$postDate)
                continue;
            if (is_numeric($postDate) && $postDate <= 1081084800) {
                $postDate = Date::excelToTimestamp($row['日期']);
            }
            $postDate = Carbon::parse($postDate)->toDateTimeString();

            Clue::updateOrCreate([
                'source' => $this->source,
                'phone' => $phone,
                'post_date' => $postDate,
            ], [
                'name'=> $row['客户昵称'],
                'question_data' => $row['备注'],
                'location' => $row['现居地'],
                'remark' => $row['微信号'],
            ]);
            $this->count++;
        }
    }
}
